package com.mcxx.modules.extremepoverty.controller;

import com.alibaba.fastjson.JSON;
import com.mcxx.modules.extremepoverty.service.ExFuneralExpenseService;
import com.mcxx.modules.miniSalvation.family.dto.FuneralDTO;
import com.mcxx.modules.miniSalvation.family.entity.FuneralEntity;
import com.mcxx.modules.miniSalvation.family.entity.OrganizationEntity;
import com.mcxx.modules.miniSalvation.family.service.read.OrganizationReadService;
import com.mcxx.modules.miniSalvation.order.entity.SuspendApproveEntity;
import com.mcxx.modules.miniSalvation.order.param.FuneralParam;
import com.mcxx.modules.miniSalvation.order.service.read.FuneralReadService;
import com.mcxx.modules.miniSalvation.order.service.write.FuneralWriteService;
import com.mcxx.service.DefaultRestService;
import com.mcxx.util.Constant;
import com.mcxx.util.FileExportUtil;
import com.mcxx.validate.group.Creation;
import com.mcxx.validate.group.Update;
import com.yinhai.ta404.component.audit.vo.ExcelInfo;
import com.yinhai.ta404.core.restservice.annotation.RestService;
import com.yinhai.ta404.core.restservice.requestbean.PageParam;
import com.yinhai.ta404.core.restservice.resultbean.Page;
import com.yinhai.ta404.core.validate.annotation.V;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Validated
@Api("丧葬费管理控制类")
@RestService({"extremePoverty/funeral/v2"})
public class ExFuneralExpenseController extends DefaultRestService {
    @Autowired
    private FuneralReadService funeralReadService;
    @Autowired
    private FuneralWriteService funeralWriteService;
    @Autowired
    private ExFuneralExpenseService exFuneralExpenseService;
    @Autowired
    private OrganizationReadService organizationReadService;


    @PostMapping("listDeadObject")
    @ApiOperation("查询状态为死亡的供养对象列表")
    public void listDeadObject(FuneralParam param, PageParam pageParam){
        log.info("查询状态为死亡的供养对象列表,查询参数：{},分页参数：{}", JSON.toJSONString(param),JSON.toJSONString(pageParam));
        Page page = funeralReadService.listDeadObject(param, pageParam, getCurUserAccount());
        setPageBean(page);
        log.info("查询状态为死亡的供养对象列表完成,结果：{}", JSON.toJSONString(page));
    }


    @PostMapping("getFuneralExpenseList")
    @ApiOperation("查询丧葬费列表")
    public void getFuneralExpenseList(FuneralParam param, PageParam pageParam){
        log.info("查询丧葬费列表,查询参数：{},分页参数：{}", JSON.toJSONString(param),JSON.toJSONString(pageParam));
        Page page = funeralReadService.listByCondition(param, pageParam, getCurUserAccount());
        setPageBean(page);
        log.info("查询丧葬费列表完成，结果：{}",JSON.toJSONString(page));
    }


    @PostMapping({"downLoadFuneralExpenseList"})
    public void downLoadFundPayListt(HttpServletResponse response, @RequestBody FuneralParam param) throws IOException {
        ExcelInfo excelInfo = exFuneralExpenseService.exportExcelFuneral(param.getExportType(),param.getIdsList(),param,getCurUserAccount());
        if(null != excelInfo){
            FileExportUtil.exportFileResponse(response, excelInfo, getCurUserAccount().getAreaName());
//            ZipInfoUtil.exportZipResponse(response, excelInfo, this.getCurUserId());
        }
    }


    @GetMapping("getFuneralById")
    @ApiOperation("根据id查询丧葬费详情")
    public void getFuneralById(@V({"notnull"}) String id){
        log.info("查询丧葬费列表,查询参数：{}", id);
        FuneralDTO funeralDTO = funeralReadService.getFuneralById(id);
        setData(funeralDTO);
        log.info("查询丧葬费详情完成，结果：{}",JSON.toJSONString(funeralDTO));
    }


    @PostMapping("addFuneralExpense")
    @ApiOperation("登记丧葬费")
    public void addFuneralExpense(@Validated(Creation.class) FuneralDTO funeralDTO){
        log.info("登记丧葬费,参数：{}", JSON.toJSONString(funeralDTO));
        funeralWriteService.addFuneralExpense(funeralDTO,getCurUserAccount());
        log.info("登记丧葬费完成");
    }


    @PostMapping("modifyFuneralExpense")
    @ApiOperation("修改丧葬费")
    public void modifyFuneralExpense(@Validated(Update.class) FuneralDTO funeralDTO){
        funeralDTO.setBusinessType(Constant.BusinessCode.TEKUN);
        log.info("修改丧葬费,参数：{}", JSON.toJSONString(funeralDTO));
        funeralWriteService.modifyFuneralExpense(funeralDTO,getCurUserAccount());
        log.info("修改丧葬费完成");
    }


    @PostMapping("delFuneralExpense")
    @ApiOperation("删除丧葬费")
    public void delFuneralExpense(@V({"notnull"}) String id){
        log.info("删除丧葬费,参数：{}", id);
        FuneralEntity entity = new FuneralEntity();
        entity.setId(id);
        funeralWriteService.delete(entity);
        log.info("删除丧葬费完成");
    }

    @GetMapping("queryOrganizationById")
    @ApiOperation("根据id查询供养机构")
    public void queryOrganizationById(@V({"notnull"}) String id){
        OrganizationEntity entity = organizationReadService.getById(id);





        setData(entity);
    }

    @PostMapping("sendAudit")
    @ApiOperation("发起审核")
    public void sendAudit(@V("notnull") @RequestPart List<FuneralDTO> funeralDTOList){
        log.info("发起审核，参数是：{}", funeralDTOList);
        Map<String, List<String>> rstMsgMap = exFuneralExpenseService.sendAudit(funeralDTOList, getCurUserAccount());
        Map<String, String> rstMap = this.packageSendAuditRst(rstMsgMap);
        setData("code", rstMap.get("code"));
        setData("msg", rstMap.get("msg"));
        log.info("发起审核，结果是：{}", rstMap);
    }


    private Map<String, String> packageSendAuditRst( Map<String, List<String>> rstMsgMap){
        Map<String, String> rstMap = new HashMap<>();
        StringBuffer rstMsg = new StringBuffer();
        if(rstMsgMap.containsKey("canNotSendAudit") == false && rstMsgMap.containsKey("noExistIdcardCert") == false
                && rstMsgMap.containsKey("noExistBankCert") == false
                && rstMsgMap.containsKey("success") ){
            rstMap.put("code", "1");
            rstMap.put("msg", "操作成功");
            return rstMap;
        }else if(rstMsgMap.containsKey("canNotSendAudit") == false && rstMsgMap.containsKey("noExistIdcardCert") == false
                && rstMsgMap.containsKey("noExistBankCert") == false
                && rstMsgMap.containsKey("fail")){
            rstMap.put("code", "-1");
            rstMap.put("msg", "操作失败");
            return rstMap;
        }
        if(rstMsgMap.containsKey("canNotSendAudit")){
            rstMsg.append("对象【").append(String.join(",",rstMsgMap.get("canNotSendAudit"))).append("】审核中，不能发起审核；\n");
        }
        if(rstMsgMap.containsKey("noExistIdcardCert")){
            rstMsg.append("【").append(String.join(",",rstMsgMap.get("noExistIdcardCert"))).append("】领取人不存在身份证证明材料，不能发起审核；\n");
        }
        if(rstMsgMap.containsKey("noExistBankCert")){
            rstMsg.append("【").append(String.join(",",rstMsgMap.get("noExistBankCert"))).append("】领取人不存在银行卡证明材料，不能发起审核；\n");
        }

        if(rstMsgMap.containsKey("success")){
            rstMsg.append("【").append(String.join(",",rstMsgMap.get("success"))).append("】发起审核成功；\n");
        }
        rstMap.put("code", "-1");
        rstMap.put("msg", rstMsg.toString());
        return rstMap;
    }


    @PostMapping("getFuneralCountyExpenseList")
    @ApiOperation("查询区县丧葬费待办列表")
    public void getFuneralCountyExpenseList(FuneralParam param, PageParam pageParam){
        log.info("查询区县丧葬费待办列表,查询参数：{},分页参数：{}", JSON.toJSONString(param),JSON.toJSONString(pageParam));
        Page page = funeralReadService.getFuneralCountyExpenseList(param, pageParam, getCurUserAccount());
        setPageBean(page);
        log.info("查询区县丧葬费待办列表，结果：{}",JSON.toJSONString(page));
    }


    @PostMapping("confirmFuneralAudit")
    @ApiOperation("审核")
    public void confirmFuneralAudit(@V("notnull") @RequestBody FuneralParam param){
        log.info("开始审核，参数是：{}", param);
        List<String> list = exFuneralExpenseService.confirmFuneralAudit(param, getCurUserAccount());
        if (!CollectionUtils.isEmpty(list)) {
            setData("code", "-1");
            setData("msg", "对象【"  + String.join(",",list)+("】的发放日期已存在名册，请驳回后重新选择发放时间；\n"));
        }
        log.info("开始审核，结果是：{}", true);
    }


    @GetMapping("getAduitInfo")
    @ApiOperation("查看审核详情")
    public void getAduitInfo(@V({"notnull"}) String id){
        log.info("查看审核详情,查询参数：{}", id);
        List<SuspendApproveEntity> suspendApproveEntityList = exFuneralExpenseService.getAduitInfo(id);
        setData(suspendApproveEntityList);
        log.info("查看审核详情完成，结果：{}",JSON.toJSONString(suspendApproveEntityList));
    }


    @PostMapping("getFuneralCountyQueryList")
    @ApiOperation("查询丧葬费已办列表")
    public void getFuneralCountyQueryList(FuneralParam param, PageParam pageParam){
        log.info("查询丧葬费已办列表,查询参数：{},分页参数：{}", JSON.toJSONString(param),JSON.toJSONString(pageParam));
        Page page = funeralReadService.getFuneralCountyQueryList(param, pageParam, getCurUserAccount());
        setPageBean(page);
        log.info("查询丧葬费已办列表，结果：{}",JSON.toJSONString(page));
    }


    @PostMapping({"downLoadFuneralSettleList"})
    public void downLoadFuneralSettleList(HttpServletResponse response, @RequestBody FuneralParam param) throws IOException {
        ExcelInfo excelInfo = exFuneralExpenseService.exportExcelFuneralSettle(param.getExportType(),param.getIdsList(),param,getCurUserAccount());
        if(null != excelInfo){
            FileExportUtil.exportFileResponse(response, excelInfo, getCurUserAccount().getAreaName());
//            ZipInfoUtil.exportZipResponse(response, excelInfo, this.getCurUserId());
        }
    }
}
